﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EnterpriseFund.Common;
using System.Data;
using DevExpress.Web.Mvc;
using DevExpress.Web.ASPxGridView;
using System.Web.UI;
using DevExpress.Utils.OAuth.Provider;
using DevExpress.XtraReports.UI;
using DevExpress.XtraPrinting;
using System.Drawing;

namespace EnterpriseFund.Controllers
{
     [OutputCache(Duration = 0, VaryByParam = "none")]
    public class QueryZZSYDBController : AdminBaseController
    {
        //
        // GET: /QueryZZSYDB/
         [AuthorityActionFilter("m_QueryZZSYDB", Order = 1)]
         [LogPageActionFilter("增值税异动表", Order = 2)]
        public ActionResult Index()
        {
            BLL.Common commonBLL = new BLL.Common();
            DataSet yds = commonBLL.GetYear();
            List<SelectListItem> yearList = new List<SelectListItem>();
            for (int i = 0; i < yds.Tables[0].Rows.Count; i++)
            {
                yearList.Add(new SelectListItem() { Text = yds.Tables[0].Rows[i]["FYear"].ToString(), Value = yds.Tables[0].Rows[i]["FYear"].ToString() });
            }
            ViewData["YearData"] = yearList;
            string year = OperateSession.get(GlobalConstant.PARAM_SYSYEAR);
            ViewData["year"] = year;
            return View();
        }
        public ActionResult QueryZZSYDBListPartial()
        {
            DataTable dt = GetModelVSBZSXX();

            return View(dt);

        }
        public ActionResult Print()
        {
            return View("");
        }
        public ActionResult ReportViewerPartial()
        {

            var zsxx = GetModelVSBZSXX();


            MVCReportGeneratonHelper generator = new MVCReportGeneratonHelper();
            generator.CustomizeColumnsCollection += new CustomizeColumnsCollectionEventHandler(generator_CustomizeColumnsCollection);
            generator.CustomizeColumn += new CustomizeColumnEventHandler(generator_CustomizeColumn);
            XtraReport report = generator.GenerateMVCReport(OperateSession.GetFromCache("QueryZZSYDB") as MVCxGridViewState, zsxx);
            //  XtraReport report = generator.GenerateMVCReport(gridViewState, dt);

            //report.PaperKind = System.Drawing.Printing.PaperKind.A4;

            this.ViewData["rpt"] = report;

            return PartialView("ReportViewerPartial");

        }
        void generator_CustomizeColumnsCollection(object source, ColumnsCreationEventArgs e)
        {


            for (int i = 0; i < e.ColumnsInfo.Count; i++)
            {

                if (e.ColumnsInfo[i].FieldName == "FFileNo")
                {
                    e.ColumnsInfo[i].ColumnWidth = 60;
                }
                if (e.ColumnsInfo[i].FieldName == "FIssueNo")
                {
                    e.ColumnsInfo[i].ColumnWidth = 80;
                }
                if (e.ColumnsInfo[i].FieldName == "NSRSBH")
                {
                    e.ColumnsInfo[i].ColumnWidth = 170;
                }
                if (e.ColumnsInfo[i].FieldName == "NSRBM")
                {
                    e.ColumnsInfo[i].ColumnWidth = 80;
                }

                if (e.ColumnsInfo[i].FieldName == "NSRMC")
                {
                    e.ColumnsInfo[i].ColumnWidth = 320;
                }

                if (e.ColumnsInfo[i].FieldName == "FFinancePropShortName")
                {
                    e.ColumnsInfo[i].ColumnWidth = 80;
                }
                if (e.ColumnsInfo[i].FieldName == "FAmount")
                {
                    e.ColumnsInfo[i].ColumnWidth = 140;
                }
                if (e.ColumnsInfo[i].FieldName == "FFileName")
                {
                    e.ColumnsInfo[i].ColumnWidth = 250;
                }
            }

        }
        void generator_CustomizeColumn(object source, ControlCustomizationEventArgs e)
        {
            if (e.FieldName == "montbnew")
            {

                XRTableCell c = e.Owner as XRTableCell;
                c.BeforePrint += new System.Drawing.Printing.PrintEventHandler(c_BeforePrint2);
            }

            if (e.FieldName == "yrtbnew")
            {

                XRTableCell c = e.Owner as XRTableCell;

                c.BeforePrint += new System.Drawing.Printing.PrintEventHandler(c_BeforePrint);

            }
            if (e.FieldName == "NSRMC")
            {

                XRTableCell c = e.Owner as XRTableCell;
                c.TextAlignment = TextAlignment.MiddleLeft;

            }
        }



        void c_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            XRTableCell c = sender as XRTableCell;
            XtraReport r = c.Report as XtraReport;
            FormattingRule rule = new FormattingRule();


            // Specify the rule's properties.

            rule.Condition = "[yrtbnew] Like '(%)'";

            rule.Formatting.ForeColor = Color.Red;
            //  rule.Formatting.Font = new Font("Arial", 10, FontStyle.Bold);

            // Apply this rule to the detail band.
            if (!r.FormattingRuleSheet.Contains(rule))
            {
                r.FormattingRuleSheet.Add(rule);
                c.FormattingRules.Add(rule);
            }






        }
        void c_BeforePrint2(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            XRTableCell c = sender as XRTableCell;
            XtraReport r = c.Report as XtraReport;
            FormattingRule rule = new FormattingRule();


            // Specify the rule's properties.

            rule.Condition = "[montbnew] Like '(%)'";

            rule.Formatting.ForeColor = Color.Red;
            //  rule.Formatting.Font = new Font("Arial", 10, FontStyle.Bold);

            // Apply this rule to the detail band.
            if (!r.FormattingRuleSheet.Contains(rule))
            {
                r.FormattingRuleSheet.Add(rule);
                c.FormattingRules.Add(rule);
            }






        }
        private DataTable GetModelVSBZSXX()
        {
            BLL.SB_ZSXX SB_ZSXXBLL = new BLL.SB_ZSXX();
            var Fyear = Request["Fyear"];
            var Fmon = Request["Fmon"];
            string dtime = Fyear.ToString() + Fmon.ToString().PadLeft(2,'0')  + "01";
            DataTable dt = SB_ZSXXBLL.GetZZSYDB(dtime, "");
            Rounddt(dt);
            return dt;
        }

        private static void Rounddt(DataTable dt)
        {
            dt.Columns.Add("yrtbnew", typeof(string));
            dt.Columns.Add("montbnew", typeof(string));

            for (int i = 0; i < dt.Rows.Count; i++)
            {

                dt.Rows[i]["se1"] = decimal.Round(string.IsNullOrEmpty(dt.Rows[i]["se1"].ToString()) ? 0 : (decimal.Parse(dt.Rows[i]["se1"].ToString()) / 10000), 2);
                dt.Rows[i]["se2"] = decimal.Round(string.IsNullOrEmpty(dt.Rows[i]["se2"].ToString()) ? 0 : (decimal.Parse(dt.Rows[i]["se2"].ToString()) / 10000), 2);
                dt.Rows[i]["se3"] = decimal.Round(string.IsNullOrEmpty(dt.Rows[i]["se3"].ToString()) ? 0 : (decimal.Parse(dt.Rows[i]["se3"].ToString()) / 10000), 2);
                dt.Rows[i]["se4"] = decimal.Round(string.IsNullOrEmpty(dt.Rows[i]["se4"].ToString()) ? 0 : (decimal.Parse(dt.Rows[i]["se4"].ToString()) / 10000), 2);
                dt.Rows[i]["se5"] = decimal.Round(string.IsNullOrEmpty(dt.Rows[i]["se5"].ToString()) ? 0 : (decimal.Parse(dt.Rows[i]["se5"].ToString()) / 10000), 2);
                if (!string.IsNullOrEmpty(dt.Rows[i]["montb"].ToString()))
                {
                    dt.Rows[i]["montbnew"] = dt.Rows[i]["montb"].ToString().Contains("-") ? ("(" + dt.Rows[i]["montb"].ToString().Substring(1) + ")") : dt.Rows[i]["montb"].ToString();
                }
                if (!string.IsNullOrEmpty(dt.Rows[i]["yrtb"].ToString()))
                {
                    dt.Rows[i]["yrtbnew"] = dt.Rows[i]["yrtb"].ToString().Contains("-") ? ("(" + dt.Rows[i]["yrtb"].ToString().Substring(1) + ")") : dt.Rows[i]["yrtb"].ToString();
                }
            }
        }
        private DataTable GetModelVSBZSXXFetch()
        {
            BLL.SB_ZSXX SB_ZSXXBLL = new BLL.SB_ZSXX();
            //var Fyear = ComboBoxExtension.GetValue<string>("Fyear");
            //var Fmon = ComboBoxExtension.GetValue<string>("Fmon");

            //根据隐藏字段 

            var Fyear = Fetch.Post("hFyear");
            var Fmon = Fetch.Post("hFmon");
            string dtime = Fyear.ToString() + Fmon.ToString().PadLeft(2, '0') + "01";
            DataTable dt = SB_ZSXXBLL.GetZZSYDB(dtime, "");
            Rounddt(dt);
            return dt;
        }
        public ActionResult ExportToXls()
        {
            var table = GetModelVSBZSXXFetch();
            return GridViewExtension.ExportToXls(ExportGridViewSettings, table, HttpUtility.UrlEncode("增值税异动表导出.xls"), true);
        }

        static GridViewSettings exportGridViewSettings;
        public static GridViewSettings ExportGridViewSettings
        {

            get
            {

                if (exportGridViewSettings == null)

                    exportGridViewSettings = CreateExportGridViewSettings();
                return exportGridViewSettings;
            }
        }

        public static GridViewSettings CreateExportGridViewSettings()
        {
            var setting = new GridViewSettings();
            setting.Name = "gvEditing";
            setting.KeyFieldName = "NSRDZDAH";
            setting.CallbackRouteValues = new { Controller = "QueryZZSYDB", Action = "QueryZZSYDBListPartial" };
            setting.Width = System.Web.UI.WebControls.Unit.Percentage(100);
            setting.SettingsPager.PageSize = EnterpriseFund.Common.GlobalConstant.CONSTRING_PAGESIZE;

            setting.Columns.Add("NSRBM", "纳税人编码");
            setting.Columns.Add("NSRMC", "纳税人名称");
            setting.Columns.Add("se1", "本月");
            setting.Columns.Add("se2", "上年同期");
            setting.Columns.Add("montbnew", "同比%").CellStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;

            setting.Columns.Add("se3", "本年累计");
            setting.Columns.Add("se4", "上年累计");
            setting.Columns.Add("yrtbnew", "同比%").CellStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
            setting.Columns.Add("se5", "上年实际");
            setting.SettingsExport.Styles.Header.BackColor = System.Drawing.Color.White;
            setting.SettingsExport.Styles.Header.ForeColor = System.Drawing.Color.Black;
            setting.SettingsExport.RenderBrick = (sender, e) =>
             {
                 if (e.Column.Caption.Contains("同比"))
                 {
                   
                     e.BrickStyle.TextAlignment = TextAlignment.MiddleCenter;
                     if (e.Text.Contains("("))
                     {
                         e.BrickStyle.ForeColor = System.Drawing.Color.Red;
                     }
                 }
             };
            setting.HtmlDataCellPrepared = (sender, e) =>
            {
                if (e.CellValue.ToString().Contains("(") & e.DataColumn.FieldName.Contains("tb"))
                {

                    e.Cell.ForeColor = System.Drawing.Color.Red;
                }

            };
            setting.SettingsBehavior.AllowFocusedRow = true;
            setting.SettingsLoadingPanel.Text = "数据读取中...";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Count, "NSRMC").DisplayFormat = "总计:";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "se1").DisplayFormat = "￥{0}";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "se2").DisplayFormat = "￥{0}";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "se3").DisplayFormat = "￥{0}";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "se4").DisplayFormat = "￥{0}";
            setting.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "se5").DisplayFormat = "￥{0}";

            setting.Settings.ShowGroupPanel = true;
            setting.Settings.ShowFooter = true;
            setting.ClientSideEvents.BeginCallback = "function(s,e){OnBeginCallback(s,e)}";
            setting.ClientSideEvents.EndCallback = "function(){}";
            setting.SettingsBehavior.EnableCustomizationWindow = true;
            setting.DataBinding = (sender, e) =>
            {
                ASPxGridView grid = (ASPxGridView)sender;
                for (int i = 0; i < grid.AllColumns.Count; i++)
                {
                    if (grid.AllColumns[i].HeaderStyle.HorizontalAlign == System.Web.UI.WebControls.HorizontalAlign.NotSet)
                    {
                        grid.AllColumns[i].HeaderStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
                    }
                }
            };
            setting.PreRender = setting.BeforeGetCallbackResult = (sender, e) =>
            {


                MVCxGridView gridView = sender as MVCxGridView;
                MVCxGridViewState gridViewState = new MVCxGridViewState(gridView);
                OperateSession.SetToCache(gridViewState, "QueryZZSYDB");


            };
            return setting;
        }



    }
}
